package com.sgb.kjwl.view.ui.adapter.self.publish;

import android.app.Activity;
import android.content.Context;
import android.content.Intent;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ImageView;
import android.widget.RelativeLayout;

import androidx.annotation.NonNull;
import androidx.recyclerview.widget.RecyclerView;

import com.bumptech.glide.Glide;
import com.luck.picture.lib.PictureSelector;
import com.luck.picture.lib.config.PictureConfig;
import com.luck.picture.lib.config.PictureMimeType;
import com.luck.picture.lib.entity.LocalMedia;
import com.sgb.kjwl.R;
import com.sgb.kjwl.model.entity.manage.UserInquiryEntity;
import com.sgb.kjwl.utils.GlideEngine;
import com.sgb.kjwl.view.ui.activity.PhotoViewActivity;
import com.swgk.core.base.CallBack;
import com.swgk.core.util.ClickUtils;
import com.swgk.core.util.DensityUtils;
import com.swgk.core.util.MToast;

import java.io.File;
import java.io.Serializable;
import java.util.ArrayList;
import java.util.Iterator;
import java.util.List;

public class ImageAdapter extends RecyclerView.Adapter<RecyclerView.ViewHolder> {

    private final LayoutInflater mLayoutInflater;
    private CallBack callBack;
    private Context mContext;
    /**
     * 选择图片后返回的LocalMedia
     **/
    private List<LocalMedia> mData;
    /**
     * 本地文件List
     **/
    private List<File> fileList;
    /**
     * 网络图片和本地图片地址组合在一起的List
     **/
    private List<String> urls;

    /**
     * 网络图片和本地图片地址组合在一起的文件
     **/
    private List<UserInquiryEntity.Companion.FileInfoEntity> fileInfo;

    /**
     * 临时存放url地址
     */
    List<String> tempUrls = new ArrayList();

    /**
     * 网络图片地址List
     **/
    private List<String> neImgList;
    private Intent intent;
    /**
     * 上传图片的最大张数
     **/
    private int maxSize;
    /**
     * 脚布局
     **/
    private int TYPE_FOOT = 1001;
    /**
     * 是否有弹窗 0：无    1：有
     **/
    private int type;
    public ISelectPop iSelectPop;
    RelativeLayout add_rl;

    public interface ISelectPop {
        void openPop();
    }

    public void OnSelectPop(ISelectPop iSelectPop) {
        this.iSelectPop = iSelectPop;
    }

    public ImageAdapter(Context context, List<LocalMedia> data, List<String> urls, int maxSize) {
        mContext = context;
        mData = new ArrayList<>();
        this.urls = new ArrayList<>();
        this.maxSize = maxSize;
        fileList = new ArrayList<>();
        neImgList = new ArrayList<>();
        fileInfo = new ArrayList<>();
        mLayoutInflater = LayoutInflater.from(context);
    }

    public ImageAdapter(Context context, List<LocalMedia> data, List<String> urls, int maxSize, CallBack callBack) {
        mContext = context;
        mData = new ArrayList<>();
        this.urls = new ArrayList<>();
        this.maxSize = maxSize;
        fileList = new ArrayList<>();
        neImgList = new ArrayList<>();
        fileInfo = new ArrayList<>();
        mLayoutInflater = LayoutInflater.from(context);
        this.callBack = callBack;
    }

    /**
     * 需要弹窗调用
     *
     * @param context
     * @param data
     * @param urls
     * @param maxSize
     * @param type
     */
    public ImageAdapter(Context context, List<LocalMedia> data, List<String> urls, int maxSize, int type) {
        mContext = context;
        mData = new ArrayList<>();
        this.urls = new ArrayList<>();
        this.maxSize = maxSize;
        fileList = new ArrayList<>();
        neImgList = new ArrayList<>();
        mLayoutInflater = LayoutInflater.from(context);
        fileInfo = new ArrayList<>();
        this.type = type;
    }

    @NonNull
    @Override
    public RecyclerView.ViewHolder onCreateViewHolder(@NonNull ViewGroup parent, int viewType) {
        if (viewType == TYPE_FOOT) {
            View headerView = mLayoutInflater.inflate(R.layout.item_device_foot, parent, false);
            return new FootViewHolder(headerView);
        }
        View inflate = mLayoutInflater.inflate(R.layout.item_image_publish, parent, false);
        return new ViewHolder(inflate);

    }

    @Override
    public void onBindViewHolder(@NonNull RecyclerView.ViewHolder holder, int position) {
        if (holder instanceof ViewHolder) {
            //如果地址包含http，就用网络加载图片的方式
            Glide.with(mContext).load(urls.get(position).trim()).into(((ViewHolder) holder).img);
            //点击图片
            ((ViewHolder) holder).img.setOnClickListener(view -> openPhotoView(position));

            //点击删除按钮
            ((ViewHolder) holder).delView.setOnClickListener(v -> {
                if (ClickUtils.isFastClick()) {
                    if (urls.get(position).contains("http")) {
                        //移除网络图片
                        if (position < neImgList.size()) {
                            neImgList.remove(position);
                        }
                    } else if (urls.get(position).contains("storage/emulated")) {
                        //移除本地LocalMedia  position减去网络图片的长度等于本地图片的位置
                        if (position - neImgList.size() >= 0 && position - neImgList.size() < mData.size()) {
                            mData.remove(position - neImgList.size());
                        }
                        //移除对应的文件
                        if (position - neImgList.size() >= 0 && position - neImgList.size() < mData.size()) {
                            fileList.remove(position - neImgList.size());
                        }
                    }
                    if (position < urls.size()) {
                        urls.remove(position);
                    }
                    notifyDataSetChanged();
                }
            });
        } else if (holder instanceof FootViewHolder) {
            add_rl.setOnClickListener(v -> {
                if (urls.size() == maxSize) {
                    MToast.showToast(mContext, "最多选择" + maxSize + "张图片");
                } else {
                    if (type == 0) {
                        openAlbum();
                    } else {
                        iSelectPop.openPop();
                    }
                }
            });
            RecyclerView.LayoutParams param = (RecyclerView.LayoutParams) add_rl.getLayoutParams();
            if (urls.size() == maxSize) {
                param.height = 0;
                param.width = 0;
                add_rl.setVisibility(View.GONE);
            } else {
                param.height = DensityUtils.dip2px(mContext, 80); // 根据具体需求场景设置
                param.width = DensityUtils.dip2px(mContext, 80);
                add_rl.setVisibility(View.VISIBLE);
            }
        }
    }

    @Override
    public int getItemCount() {
        if (maxSize == 1 || urls.size() == 0) {
            return 1;
        } else { //加了头布局,多一个
            return urls.size() + 1;
        }


    }

    @Override
    public int getItemViewType(int position) {
        //在第一个位置添加头
        if (urls.size() != 0) {
            if (position == urls.size()) {
                return TYPE_FOOT;
            }
        } else {
            if (position == 0) {
                return TYPE_FOOT;
            }
        }
        return super.getItemViewType(position);
    }

    //设置本地图片
    public void setDatas(List<LocalMedia> mData, List<String> urls) {
        //防止图片重复  可优化
        this.urls.clear();
        this.urls.removeAll(urls);
        if (neImgList.size() != 0) {
            this.urls.addAll(neImgList);
        }/* else {
            this.urls.clear();
        }*/
        this.urls.addAll(urls);
        this.mData = mData;
        notifyDataSetChanged();
    }

    //设置本地图片 函询目前使用
    public void setData(List<LocalMedia> mData, List<UserInquiryEntity.Companion.FileInfoEntity> fileInfos) {
        tempUrls.clear();
        for (UserInquiryEntity.Companion.FileInfoEntity entity : fileInfos) {
            tempUrls.add(entity.getFileUrl());
        }
        this.fileInfo.addAll(fileInfos);
        this.setDatas(mData, tempUrls);
    }

    /**
     * 设置图片文件List
     **/
    public void setFileList(List<File> fileList) {
        this.fileList = fileList;
    }

    /**
     * 设置网络图片List
     */
    public void setNetImgList(List<String> netImgList) {
        if (netImgList == null) {
            this.neImgList = new ArrayList<>();
        } else {
            this.neImgList = new ArrayList<>(netImgList);
            this.urls.addAll(netImgList);
        }
        notifyDataSetChanged();
    }

    /**
     * 添加网络图片List
     */
    public void addNetImgList(List<String> netImgList) {
        this.neImgList.addAll(netImgList);
        this.urls.addAll(netImgList);
        notifyDataSetChanged();
    }

    /**
     * 删除重复的网络图片List
     * 有点问题(取消后从网络图库中取消不会取消)
     */
    public void updateNetImgList(List<String> selcetUrl, List<String> unSelcetUrl) {
        //去除选中图片中相同的图片（先移除以前选择过的图片）
        for (int a = 0; a < neImgList.size(); a++) {
            for (Iterator<String> iterator = selcetUrl.iterator(); iterator.hasNext(); ) {
                if (neImgList.get(a).equals(iterator.next())) {
                    iterator.remove();
                }
            }
        }
        //去除原来选中后来取消的图片(在移除原来选中现在取消了的图片)
        for (int b = 0; b < unSelcetUrl.size(); b++) {
            for (Iterator<String> iterator = neImgList.iterator(); iterator.hasNext(); ) {
                if (unSelcetUrl.get(b).equals(iterator.next())) {
                    iterator.remove();
                }
            }
        }
        //去除中集合中的已经取消的图片
        for (int c = 0; c < unSelcetUrl.size(); c++) {
            for (Iterator<String> iterator = urls.iterator(); iterator.hasNext(); ) {
                if (unSelcetUrl.get(c).equals(iterator.next())) {
                    iterator.remove();
                }
            }
        }
        neImgList.addAll(selcetUrl);
        urls.addAll(selcetUrl);
        notifyDataSetChanged();
    }

    /**
     * 获取已选择的本地文件List
     **/
    public List<File> getFileList() {
        return this.fileList;
    }

    /**
     * 获取所有的地址List，包括网络和本地
     **/
    public List<String> getUrls() {
        return urls;
    }

    /**
     * 获取所有的地址List，包括网络和本地
     **/
    public List<UserInquiryEntity.Companion.FileInfoEntity> getfileInfos() {
        return fileInfo;
    }

    /**
     * 获取网络图片地址List
     **/
    public List<String> getNetUrls() {
        return neImgList;
    }

    /**
     * 获取已选择的LocalMedia List
     **/
    public List<LocalMedia> getLocalMedia() {
        return mData;
    }

    /**
     * 预览
     **/
    private void openPhotoView(int position) {
        if (intent == null) {
            intent = new Intent();
        }
        intent.setClass(mContext, PhotoViewActivity.class);
        intent.putExtra(PhotoViewActivity.KEY_PHOTO_URLS, (Serializable) urls);
        intent.putExtra(PhotoViewActivity.KEY_PHOTO_POSITION, position);
        mContext.startActivity(intent);
    }

    /**
     * 尾布局的viewholder
     */
    class FootViewHolder extends RecyclerView.ViewHolder {
        ;

        FootViewHolder(View itemView) {
            super(itemView);
            add_rl = itemView.findViewById(R.id.add_rl);
        }
    }


    /**
     * 正常内容的viewholder
     */
    class ViewHolder extends RecyclerView.ViewHolder {
        ImageView img;
        ImageView delView;

        ViewHolder(View itemView) {
            super(itemView);
            img = itemView.findViewById(R.id.photo_img);
            delView = itemView.findViewById(R.id.delete_tv);
        }
    }

    public void openAlbum() {
        if (callBack != null) {
            callBack.onFailed(0, 0, "选择图片");
        }
        PictureSelector.create((Activity) mContext)
                .openGallery(PictureMimeType.ofImage())
                .loadImageEngine(GlideEngine.createGlideEngine())
                .theme(R.style.picture_default_style)
                .maxSelectNum(maxSize - neImgList.size())//判断还能选多少张图片
                .compress(true)//是否压缩
                .minimumCompressSize(1024)//小于1M不压缩
                .selectionMedia(mData)
                .forResult(PictureConfig.CHOOSE_REQUEST);
    }

    public void openAlbum(int CHOOSE_REQUEST) {
        if (callBack != null) {
            callBack.onFailed(0, 0, "选择图片");
        }
        PictureSelector.create((Activity) mContext)
                .openGallery(PictureMimeType.ofImage())
                .loadImageEngine(GlideEngine.createGlideEngine())
                .theme(R.style.picture_default_style)
                .maxSelectNum(maxSize - neImgList.size())//判断还能选多少张图片
                .compress(true)//是否压缩
                .minimumCompressSize(1024)//小于1M不压缩
                .selectionMedia(mData)
                .forResult(CHOOSE_REQUEST);
    }
}